package fastwave.cloud.sb.controller;

import fastwave.cloud.demo.fastwavelibcommon.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Map;

@RestController
@RequestMapping("/auth")
public class AuthController {

    @Value("${server.port}")
    Integer port;

    @GetMapping("/hasPermission")
    public R hasPermission(@RequestParam Map<String,Object> params) throws Exception {
        Object token = params.get("token");
        InetAddress ip = InetAddress.getLocalHost();// 获取本地IP对象
        String mac =  getMACAddress(ip);

        String ipAndMac = String.format("本机的ip:%s,mac:%s",ip, mac);

        if(token != null && token.toString().length() > 5)
        {
            return R.ok(ipAndMac + ",验证成功V5，port=" + port.toString());
        }

        if(token.toString().indexOf("error") != -1)
        {
            throw  new Exception(ipAndMac + ",出错了");
        }

        if(token.toString().indexOf("long") != -1)
        {
            Long s = Long.parseLong(params.get("s").toString());
            Thread.sleep(s);
            return R.error(ipAndMac + ",验证失败V5，等待了" + s + " 毫秒，port=" + port.toString());
        }

        return R.error(ipAndMac + ",验证失败V5，port=" + port.toString());
    }



    @PostMapping("/hasPermission")
    public R hasPermissionByPost(@RequestBody Map<String,Object> params) throws InterruptedException {
        Object token = params.get("token");
        if(token != null && token.toString().length() > 5)
        {
            return R.ok("验证成功V3，port=" + port.toString());
        }

        //Thread.sleep(2000L);
        return R.error("验证失败V3，port=" + port.toString());
    }

    // 获取MAC地址的方法
    private static String getMACAddress(InetAddress ia) throws Exception {
        // 获得网络接口对象（即网卡），并得到mac地址，mac地址存在于一个byte数组中。
        byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
        // 下面代码是把mac地址拼装成String
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < mac.length; i++) {
            if (i != 0) {
                sb.append("-");
            }
            // mac[i] & 0xFF 是为了把byte转化为正整数
            String s = Integer.toHexString(mac[i] & 0xFF);
            // System.out.println("--------------");
            // System.err.println(s);
            sb.append(s.length() == 1 ? 0 + s : s);
        }
        // 把字符串所有小写字母改为大写成为正规的mac地址并返回
        return sb.toString().toUpperCase();
    }
}
